// \u4e00-\u9fa5] 中文验证规则
import wxValidate from 'wechat-validate'
Page({
  behaviors: [wxValidate],
  data: {
    point: '',
    building: '',
    room: '',
    name: '',
    gender: [0, 1],
    mobile: '',

    idcardFrontUrl: '',
    idcardBackUrl: '',
  },
  rules: {
    name: [
      {
        required: true,
        message: '业主姓名不能为空!',
      },
      {
        pattern: /^[\u4e00-\u9fa5]{2,5}$/,
        message: '业主姓名只能为中文!',
      },
    ],
    mobile: [
      {
        required: true,
        message: '业主手机号不能为空!',
      },
      {
        pattern: /^1[3-8]\d{9}$/,
        message: '请填写正确的手机号!',
      },
    ],
    idcardFrontUrl: [
      {
        required: true,
        message: '请上传身份证国徽面!',
      },
    ],
    idcardBackUrl: [
      {
        required: true,
        message: '请上传身份证照片面!',
      },
    ],
  },
  onLoad({ point, building, room, id }) {
    console.log(id)
    if (id) return this.getDetail(id)
    if (id) {
      wx.setNavigationBarTitle({
        title: id ? '修改房屋信息' : '新增房屋信息',
      })
    }
    this.setData({
      point,
      building,
      room,
    })
  },
  async getDetail(id) {
    const { code, data } = await wx.http.get('/room/' + id)
    if (code !== 10000) return wx.utils.toast()
    this.setData({ ...data })
  },
  async submitForm() {
    if (!this.validate()) return
    //获取全部数据
    const { __webviewId__, status, ...data } = this.data
    const { code } = await wx.http.post('/room', data)
    //检测是否调用成功
    if (code !== 10000) return wx.utils.toast('提交数据失败!')
    // 返回房屋列表页面

    wx.navigateBack({ delta: this.data.id ? 2 : 4 })
  },
  async uploadPicture(ev) {
    const type = ev.mark.type
    try {
      const media = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed'],
      })
      console.log(media)
      //调用api
      wx.uploadFile({
        url: wx.http.baseURL + '/upload',
        filePath: media.tempFiles[0].tempFilePath,
        name: 'file',
        header: {
          Authorization: 'Bearer ' + getApp().token,
        },
        success: (result) => {
          console.log(result)
          // 处理返回数据
          const data = JSON.parse(result.data)
          // 判断是否调用成功
          if (data.code !== 10000) return wx.utils.toast('上传图片失败!')
          // 渲染
          this.setData({
            [type]: data.data.url,
          })
        },
      })
    } catch (err) {
      console.log(err)
    }
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark.type
    this.setData({
      [type]: '',
    })
  },
})
